﻿using System.Collections;
using System;
using Random = UnityEngine.Random;
using System.Collections.Generic;
using UnityEngine;

public class BoardManager : MonoBehaviour {
	[Serializable]
	public class Range{
        public int minium { get; private set; }
        public int maxium { get; private set; }
		public Range(int min, int max){
			minium = min;
			maxium = max;
		}
	}

	public int Columns = 7;
	public int Rows = 7;
	public Range WallCount = new Range(5, 9);
	public Range FoodCount = new Range(1, 5);
	public GameObject[] WallTiles;
	public GameObject[] OuterWallTiles;
	public GameObject[] FloorTiles;
	public GameObject[] EnemyTiles;
	public GameObject[] FoodTiles;
    public GameObject Exit;

	private Transform boardHolder;
	private List<Vector3> gridPostions = new List<Vector3>();

	void InitialseList(){
		for (int x = 1; x < Rows - 1; x++) {
			for (int y = 1; y < Columns - 1; y++){
				gridPostions.Add(new Vector3(x, y, 0f));
			}
		}
	}

	void BoardSetup(){
		boardHolder = new GameObject ("board").transform;
		for (int x = -1; x < Rows + 1; x++) {
			for (int y = -1; y < Columns + 1; y++) {
				GameObject toInstantiate = null;
                if (x == -1 || y == -1 || x == Rows || y == Columns)
                {
                    toInstantiate = OuterWallTiles[Random.Range(0, OuterWallTiles.Length)];
                }
                if (toInstantiate != null)
                {
                    var instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), Quaternion.identity) as GameObject;
                    instance.transform.SetParent(boardHolder);
                }
			}
		}
	}

	Vector3 RandomPos(){
		var randomIndex = Random.Range (0, gridPostions.Count);
		var pos = gridPostions [randomIndex];
		gridPostions.RemoveAt (randomIndex);
		return pos;
	}

	void RandomlyGenerate(GameObject[] objectList, Range range){
		int genCount = Random.Range(range.minium, range.maxium);
		for (int i = 0; i < genCount; i++) {
			var chosenObj = objectList [Random.Range (0, objectList.Length)];
			var chosenPos = RandomPos ();
			Instantiate (chosenObj, chosenPos, Quaternion.identity);
		}
	}

    void LayoutGamePad(){
        for (int x = 0; x < Rows; x ++){
            for (int y = 0; y < Columns; y++){
                Instantiate(FloorTiles[Random.Range(0, FloorTiles.Length)], new Vector3(x, y, 0f), Quaternion.identity);
            }
        }
    }

	public void SetupSence(int level){
		BoardSetup ();
		InitialseList ();
        LayoutGamePad();
		RandomlyGenerate (FoodTiles, FoodCount);
		RandomlyGenerate (WallTiles, WallCount);
		RandomlyGenerate (EnemyTiles, new Range((int)Math.Log(level,2), (int)Math.Log(level,2)));
		Instantiate(Exit, new Vector3(Rows - 1, Columns - 1, 0.0f), Quaternion.identity);
	}
}
